<template>
  <div class="order-detail-container">
    <el-card shadow="never" class="detail-card">
      <!-- 订单头部 -->
      <div class="order-header">
        <el-tag
          :type="statusTagType"
          effect="dark"
          size="medium"
        >
          {{ statusName }}
        </el-tag>
        <span class="order-id">订单号：{{ orderInfo.orderId }}</span>
      </div>

      <!-- 基本信息 -->
      <el-descriptions :column="2" border>
        <el-descriptions-item label="下单时间" label-class-name="desc-label">
          {{ orderInfo.createTime }}
        </el-descriptions-item>
        <el-descriptions-item label="支付方式" label-class-name="desc-label">
          {{ orderInfo.paymentMethod }}
        </el-descriptions-item>
        <el-descriptions-item label="商品金额" label-class-name="desc-label">
          ￥{{ orderInfo.totalAmount.toFixed(2) }}
        </el-descriptions-item>
        <el-descriptions-item label="配送费用" label-class-name="desc-label">
          ￥{{ orderInfo.deliveryFee.toFixed(2) }}
        </el-descriptions-item>
        <el-descriptions-item label="订单总额" :span="2" label-class-name="desc-label">
          <span class="total-amount">
            ￥{{ orderInfo.actualAmount.toFixed(2) }}
          </span>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 商品明细 -->
      <div class="goods-section">
        <h3 class="section-title">商品明细</h3>
        <el-table
          :data="orderItems"
          :show-header="false"
          :row-style="{ height: '80px' }"
          :cell-style="{ padding: '8px' }"
          class="goods-table"
        >
          <el-table-column width="80">
            <template slot-scope="scope">
              <div class="custom-cell">
                <el-image
                  :src="scope.row.imageUrl"
                  class="goods-image"
                  fit="cover"
                >
                </el-image>
              </div>
            </template>
          </el-table-column>
          <el-table-column>
            <template slot-scope="scope">
              <div class="goods-info">
                <div class="goods-name">{{ scope.row.productName }}</div>
                <div class="goods-spec">
                  {{ scope.row.productPrice | priceFormat }} × {{ scope.row.quantity }}件
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="120" align="right">
            <template slot-scope="scope">
              <div class="goods-total">
                ￥{{ scope.row.itemAmount.toFixed(2) }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 操作按钮 -->
      <div class="action-bar">
        <el-button
          type="primary"
          plain
          :loading="btnLoading"
          @click="handleBack"
        >
          返回列表
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
const debounce = (func, wait = 500) => {
  let timeout
  return function (...args) {
    const context = this
    clearTimeout(timeout)
    timeout = setTimeout(() => {
      func.apply(context, args)
    }, wait)
  }
}

export default {
  name: 'OrderItem',
  data() {
    return {
      btnLoading: false,
      orderId: '',
      statusName: '',
      orderInfo: {},
      orderItems: []
    }
  },
  created() {
    this.orderId = this.$route.query.orderId
    this.debouncedFetch = debounce(this.fetchOrderDetails)
    this.debouncedBack = debounce(this.handleRealBack)
    this.fetchOrderDetails()
  },
  computed: {
    statusTagType() {
      const statusMap = {
        1: 'info',    // 待支付
        2: 'success', // 已支付
        3: '',        // 已分拣
        4: 'warning', // 配送中
        5: 'success', // 已完成
        6: 'danger'   // 已取消
      }
      return statusMap[this.orderInfo.statusId] || 'info'
    }
  },
  methods: {
    async fetchOrderDetails() {
      try {
        const res = await this.$axios.get(`api/order/queryOrderItem/${this.orderId}`)
        if (res.data.code === 200) {
          const data = res.data.data
          this.statusName = data.statusName
          this.orderItems = data.orderItemDTOList
          this.orderInfo = {
            orderId: data.orderId,
            createTime: data.createTime,
            paymentMethod: data.paymentMethodName,
            address: data.address,
            totalAmount: data.totalAmount,
            deliveryFee: data.deliveryFee,
            actualAmount: data.actualAmount,
            deliveryTime: data.deliveryTime,
            statusId: data.statusId
          }
        }
      } catch (error) {
        console.error('订单详情加载失败', error)
        this.$message.error('数据加载失败，请稍后重试')
      }
    },

    handleBack() {
      this.btnLoading = true
      this.debouncedBack().finally(() => {
        this.btnLoading = false
      })
    },

    handleRealBack() {
      this.$router.push({ path: '/orders' })
    }
  }
}
</script>

<style lang="scss" scoped>
.order-detail-container {
  padding: 20px;

  .detail-card {
    ::v-deep .el-card__body {
      padding: 30px;
    }

    .order-header {
      margin-bottom: 25px;
      padding-bottom: 20px;
      border-bottom: 1px solid #ebeef5;

      .order-id {
        margin-left: 20px;
        color: #909399;
        font-size: 14px;
      }
    }

    .desc-label {
      width: 100px;
      text-align: center;
      background: #f5f7fa !important;
    }

    .total-amount {
      color: #f56c6c;
      font-size: 18px;
      font-weight: 600;
    }

    .goods-section {
      margin-top: 30px;

      .section-title {
        margin-bottom: 15px;
        color: #303133;
        font-size: 16px;
      }

      .goods-table {
        margin-top: 10px;
        
        .custom-cell {
          // 禁用默认文本截断
          .cell {
            white-space: normal !important;
            overflow: visible !important;
            text-overflow: clip !important;
          }
        }

        .goods-image {
          width: 60px;
          height: 60px;
          border-radius: 4px;
        }

        .goods-info {
          padding-left: 15px;

          .goods-name {
            margin-bottom: 8px;
            font-weight: 500;
          }

          .goods-spec {
            color: #909399;
            font-size: 12px;
          }
        }

        .goods-total {
          font-weight: 600;
          color: #f56c6c;
        }
      }
    }

    .action-bar {
      margin-top: 30px;
      text-align: center;
    }
  }
}
</style>